package com.sc.userspringboot.interceptor;

import com.alibaba.fastjson.JSON;
import com.sc.userspringboot.pojo.Users;
import com.sc.userspringboot.utils.JwtUtils;
import com.sc.userspringboot.utils.ResponseMsg;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放过登录接口
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/users/login") || requestURI.contains("/users/register")) {
            return true;
        }

        String jwtToken = request.getHeader("token");

        try {
            // 验证token
            Claims claims = JwtUtils.parseJWT(jwtToken);
            Users users = JSON.parseObject(claims.getSubject(), Users.class);

            // 判断token是否可用
            if (!JwtUtils.isAvailable(users.getEmail())) {
                response.setStatus(401);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(ResponseMsg.getInstance(ResponseMsg.TOKEN_EXPIRED, "token失效")));
                return false;
            }

            return true;
        } catch (Exception e) {
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ResponseMsg.getInstance(ResponseMsg.TOKEN_INVALID, "验证jwt失败,出现异常")));
            return false;
        }
    }
}
